﻿using System;
using System.Reflection;
using DC2010.Objects.Data;
using log4net;
using DC2010.Conditions;


namespace DC2010.Systems
{
    /// <summary>
    /// This system is here for conditional purposes. Sometimes we need to define that
    /// something happens ONLY IF or ONLY IF NOT. For this reason this class is here.
    /// </summary>
    public class ConditionSystem : BaseSystem<ConditionInfo, ConditionGfx, ConditionData>
    {
        public InstancesConditions Instances { get; set; }

        public override void Init(string code)
        {
            IsUsingInfo = true;
            IsUsingData = true;
			IsUsingGfx = false;
		
            InfoFileName = "Data\\" + code + "Info.xml";
            GfxFileName = "Data\\" + code + "Gfx.xml";
            DataFileName = "Temp\\" + code + "Data.xml";

            Code = code;

            DateTime dtStart = DateTime.Now;

            base.Init(code);

            //prepare effects for common use
            Instances = new InstancesConditions();

            log.Info("Core, Conditions init takes: " + (DateTime.Now - dtStart).TotalSeconds+" seconds");
        }

        /// <summary>
        /// Method will create new instance of effect. Definition of this effect is in EffectData. EffectData 
        /// is passed as parametr to Effect.
        /// </summary>
        /// <param name="ed"></param>
        /// <returns></returns>
        public ConditionLogic InstantiateCondition(ConditionData ed)
        {
            //Effect are stored in "DC2010.Conditions" namespace

            ConditionInfo ei = GetInfo(ed.InfoId);
            string FullName = "DC2010.Conditions." + ei.Method;

            try
            {
                Assembly assembly = Assembly.GetCallingAssembly();
                Type type = assembly.GetType(FullName);

                object o = Activator.CreateInstance(type, ed);

                if ((o != null) && (o is ConditionLogic))
                {
                    //this is place where all intance are alive
                    AddData(ed);

                    //return created condition
                    return (ConditionLogic)o;
                }
            }
            catch (Exception)
            {
                return null;
                //log
            }

            return null;
        }
    }
}
